package ca.etsmtl.log240.financej;
/*
 * Account.java
 *
 * Created on March 5, 2008, 11:08 PM
 */

import java.sql.*;
import javax.swing.table.*;
import javax.swing.*;

/**
 *
 * @author  rovitotv
 */
public class Account extends javax.swing.JDialog {

	private Connection conn = null;
	private AccountListTableModel dataModel;

	/** Creates new form Account */
	public Account(java.awt.Frame parent, boolean modal) {
		super(parent, modal);
		initComponents();
		accountListTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
	}

	public void setDBConnection(Connection dBConn) {
		conn = dBConn;
		dataModel = new AccountListTableModel(conn);
		accountListTable.setModel(dataModel);
	}

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
	private void initComponents() {

		closeButton = new javax.swing.JButton();
		jScrollPane1 = new javax.swing.JScrollPane();
		accountListTable = new javax.swing.JTable();
		deleteAccountButton = new javax.swing.JButton();
		jPanel1 = new javax.swing.JPanel();
		addAccountButton = new javax.swing.JButton();
		nameTextField = new javax.swing.JTextField();
		descriptionTextField = new javax.swing.JTextField();
		jLabel1 = new javax.swing.JLabel();
		jLabel2 = new javax.swing.JLabel();

		setTitle("Accounts");
		setModal(true);
		setName("AccountDialog"); // NOI18N

		closeButton.setText("Close");
		closeButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				closeButtonActionPerformed(evt);
			}
		});

		accountListTable.setModel(new javax.swing.table.DefaultTableModel(
				new Object [][] {
						{null, null}
				},
				new String [] {
						"Name", "Description"
				}
		) {
			Class[] types = new Class [] {
					java.lang.String.class, java.lang.String.class
			};

			public Class getColumnClass(int columnIndex) {
				return types [columnIndex];
			}
		});
		jScrollPane1.setViewportView(accountListTable);
		accountListTable.getColumnModel().getColumn(0).setPreferredWidth(25);

		deleteAccountButton.setText("Delete Account");
		deleteAccountButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				deleteAccountButtonActionPerformed(evt);
			}
		});

		addAccountButton.setText("Add Account");
		addAccountButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				addAccountButtonActionPerformed(evt);
			}
		});

		jLabel1.setText("Name:");

		jLabel2.setText("Description:");

		javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
		jPanel1.setLayout(jPanel1Layout);
		jPanel1Layout.setHorizontalGroup(
				jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
						.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
								.addGroup(jPanel1Layout.createSequentialGroup()
										.addContainerGap()
										.addComponent(addAccountButton))
										.addGroup(jPanel1Layout.createSequentialGroup()
												.addGap(117, 117, 117)
												.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
														.addComponent(jLabel1)
														.addComponent(jLabel2))
														.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
														.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
																.addComponent(nameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 277, Short.MAX_VALUE)
																.addComponent(descriptionTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 277, Short.MAX_VALUE))))
																.addGap(24, 24, 24))
		);
		jPanel1Layout.setVerticalGroup(
				jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(jPanel1Layout.createSequentialGroup()
						.addContainerGap()
						.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
								.addComponent(jLabel1)
								.addComponent(nameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
								.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
										.addComponent(jLabel2)
										.addComponent(descriptionTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
										.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
										.addComponent(addAccountButton)
										.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
		);

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(
				layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
						.addContainerGap()
						.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 471, Short.MAX_VALUE)
						.addContainerGap())
						.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
								.addContainerGap(279, Short.MAX_VALUE)
								.addComponent(deleteAccountButton)
								.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addComponent(closeButton)
								.addGap(31, 31, 31))
								.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
		);
		layout.setVerticalGroup(
				layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
						.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addGap(18, 18, 18)
						.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 198, Short.MAX_VALUE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
								.addComponent(deleteAccountButton)
								.addComponent(closeButton))
								.addContainerGap())
		);

		pack();
	}// </editor-fold>//GEN-END:initComponents
	private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CloseButtonActionPerformed
		setVisible(false);
	}//GEN-LAST:event_CloseButtonActionPerformed

	private void deleteAccountButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DeleteAccountButtonActionPerformed
		if (accountListTable.getSelectionModel().getLeadSelectionIndex() >= 0) {
			System.out.println("delete row:" + accountListTable.getSelectionModel().getLeadSelectionIndex());
			dataModel.deleteAccount(accountListTable.getSelectionModel().getLeadSelectionIndex());
		} else { //nothing selected give error messge
			JOptionPane.showMessageDialog(this,
					"No account selected to delete, please select an account then click the delete button.",
					"Error", JOptionPane.ERROR_MESSAGE);
		}
	}//GEN-LAST:event_DeleteAccountButtonActionPerformed

	private void addAccountButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddAccountButtonActionPerformed
		int ReturnCode;

		ReturnCode = dataModel.AddAccount(nameTextField.getText(), descriptionTextField.getText());
		if (ReturnCode == 0) {
			nameTextField.setText("");
			descriptionTextField.setText("");
		} else {
			JOptionPane.showMessageDialog(this,
					"Error Adding account to database.  Make sure the account name you specified does not already exist.",
					"Error", JOptionPane.ERROR_MESSAGE);
		}
	}//GEN-LAST:event_AddAccountButtonActionPerformed

	/**
	 * @param args the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {

			public void run() {
				Account dialog = new Account(new javax.swing.JFrame(), true);
				dialog.addWindowListener(new java.awt.event.WindowAdapter() {

					public void windowClosing(java.awt.event.WindowEvent e) {
						System.exit(0);
					}
				});
				dialog.setVisible(true);
			}
		});
	}
	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.JTable accountListTable;
	private javax.swing.JButton addAccountButton;
	private javax.swing.JButton closeButton;
	private javax.swing.JButton deleteAccountButton;
	private javax.swing.JTextField descriptionTextField;
	private javax.swing.JTextField nameTextField;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JLabel jLabel2;
	private javax.swing.JPanel jPanel1;
	private javax.swing.JScrollPane jScrollPane1;
	// End of variables declaration//GEN-END:variables
}

class AccountListTableModel extends AbstractTableModel {

	private String[] columnNames = {"Name", "Description"};
	private Connection conn = null;

	public AccountListTableModel(Connection dBConn) {
		conn = dBConn;
	}

	public int getColumnCount() {
		return columnNames.length;
	}

	public int getRowCount() {
		ResultSet AccountResult;
		Statement s;

		if (conn != null) {
			try {
				s = conn.createStatement();
				AccountResult = s.executeQuery("select count(name) from account");
				while (AccountResult.next()) {
					return AccountResult.getInt(1);
				}
			} catch (Throwable e) {
				System.out.println(" . . . exception thrown: in AccountListTableModel getRowCount");
				e.printStackTrace();
			}
		}

		return 0;
	}

	public String getColumnName(int col) {
		return columnNames[col];
	}

	public Object getValueAt(int row, int col) {
		ResultSet AccountResult;
		Statement s;
		int CurrentRow = 0;

		if (conn != null) {
			try {
				s = conn.createStatement();
				AccountResult = s.executeQuery("select * from account order by name");
				while (AccountResult.next()) {
					if (CurrentRow == row) {
						if (col == 0) {
							return AccountResult.getString(1);
						} else if (col == 1) {
							return AccountResult.getString(2);
						}
					}
					CurrentRow++;
				}
			} catch (Throwable e) {
				System.out.println(" . . . exception thrown: in AccountListTableModel getValueAt");
				e.printStackTrace();
			}
		}
		return "";
	}

	public Class getColumnClass(int c) {
		return getValueAt(0, c).getClass();
	}

	/*
	 * Don't need to implement this method unless your table's
	 * editable.
	 */
	public boolean isCellEditable(int row, int col) {
		//Note that the data/cell address is constant,
		//no matter where the cell appears onscreen.


		if (col == 0) {
			return false;
		} else {
			return true;
		}
	}

	public void setValueAt(Object value, int row, int col) {
		String SQLString;

		String AccountName;
		try {
			AccountName = (String) getValueAt(row, 0);
			Statement s = conn.createStatement();
			SQLString = "update account set description ='" + (String) value + "' where name = '" + AccountName + "'";
			System.out.println(SQLString);
			s.execute(SQLString);

			fireTableCellUpdated(row, col);
		} catch (Throwable e) {
			System.out.println(" . . . exception thrown: in setValueAt in Account.java");
			e.printStackTrace();
		}
	}

	public void deleteAccount(int row) {
		Statement s;
		String AccountName;
		String SQLString;

		if (conn != null) {
			try {
				AccountName = (String) getValueAt(row, 0);
				s = conn.createStatement();
				SQLString = "DELETE FROM account WHERE name = '" + AccountName + "'";
				System.out.println(SQLString);
				s.executeUpdate(SQLString);
				fireTableDataChanged();
			} catch (Throwable e) {
				System.out.println(" . . . exception thrown: in AccountListTableModel DeleteAccount");
				e.printStackTrace();
			}
		}
	}

	public int AddAccount(String name, String description) {
		int ErrorCode = 0;
		PreparedStatement psInsert;

		try {
			psInsert = conn.prepareStatement("insert into account(name, description) values(?,?)");
			psInsert.setString(1, name);
			psInsert.setString(2, description);

			psInsert.executeUpdate();
			fireTableRowsInserted(getRowCount() + 1, getRowCount() + 1);
		} catch (Throwable e) {
			System.out.println(" . . . exception thrown: AddAccount");
			e.printStackTrace();
			ErrorCode = 1;
		}

		return ErrorCode;
	}
}
